<template>
  <div>
    <div>
      <UploadExcel :on-success="upload" />
    </div>
  </div>
</template>

<script>
// import UploadExcel from '@/components/UploadExcel/index.vue'
import { importEmployees } from '@/api/employees'
export default {
  components: {
    // UploadExcel
  },
  methods: {
    async upload(data) {
      console.log('上传成功')
      console.log(data)
      const users = data.results.map(user => {
        // 分离函数翻译用户key
        return this.zh2en(user)
      })

      // 数据转换完毕 发送请求
      // 发送完毕
      await importEmployees(users)
      // 提醒用户
      this.$message.success('导入成功')
      // 回到员工页
      // this.$router.push('/employees')
      this.$router.back()
      // console.log(users)
    },
    zh2en(user) {
      const newUsers = {}
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      for (const key in user) {
        const enKey = headers[key]
        const value = user[key]
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          // 转日期格式, 函数可以转字符串, 再交给 new Date() 形成日期对象
          newUsers[enKey] = new Date(this.formatDateExcel(value, '/'))
        } else {
          // 正常使用 value 即可
          newUsers[enKey] = value
        }
      }
      // console.log(newUsers)
      return newUsers
    },
    // 上传 excel 时间格式化
    formatDateExcel(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }

}
</script>

<style>

</style>
